package com.uziot.bucket.common.util;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能描述: <br>
 * 参数校验工具
 *
 * @author shidt
 * @date 2020-08-22 10:21
 */
public class ValidatorUtil {
    private static final Validator VALIDATOR_FAST;
    private static final Validator VALIDATOR_LAZY;

    static {
        VALIDATOR_FAST = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(true)
                .buildValidatorFactory()
                .getValidator();
        VALIDATOR_LAZY = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(false)
                .buildValidatorFactory()
                .getValidator();
    }

    /**
     * 对象校验，遇到一个异常则抛出
     *
     * @param object 需要校验的对象
     * @param group  分组
     * @param <T>    对象类型
     * @throws RuntimeException 异常
     */
    public static <T> void validate(T object, Class<?>... group) throws RuntimeException {
        Set<ConstraintViolation<T>> results = VALIDATOR_FAST.validate(object, group);
        if (!results.isEmpty()) {
            for (ConstraintViolation<T> constraintViolation : results) {
                throw new RuntimeException(constraintViolation.getMessageTemplate());
            }
        }
    }

    /**
     * 不抛出异常，获取所有校验结果
     *
     * @param object 需要校验的对象
     * @param group  分组
     * @param <T>    泛型
     * @return 结果消息
     */
    public static <T> HashSet<String> getValidateResult(T object, Class<?>... group) {
        Set<ConstraintViolation<T>> results = VALIDATOR_LAZY.validate(object, group);
        HashSet<String> result = new HashSet<>();
        results.forEach(res -> {
            result.add(res.getMessageTemplate());
        });
        return result;
    }
}
